<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车间任务编号" prop="sn" label-width="55">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入车间任务编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:task:add']"
        >新增车间任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:task:export']"
        >导出</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="taskList" border style="width: 100%" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" prop="number" />
      <el-table-column label="任务状态" align="center" prop="state" width="110">
      <template v-slot = "scope">
        <dict-tag :options="dict.type.task_state" :value="scope.row.state"/>
      </template>
      </el-table-column>
      <el-table-column label="生产进度" align="center" :width="150">
        <template v-slot="{ row }">
          <div class="demo-progress">
            <el-progress :text-inside="true" :stroke-width="15" :percentage="calculateProgressPercentage(row.planNum, row.gbtNum)" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="车间任务编号" align="center" prop="sn" width="150" />
<!--      <el-table-column label="领料id" align="center" prop="materId" />-->
<!--      <el-table-column label="产品id" align="center" prop="proId" />-->
      <el-table-column label="车间任务名称" align="center" prop="name" width="120" />
      <el-table-column label="产品名称" align="center" prop="proName" width="120"/>
      <el-table-column label="产品编码" align="center" prop="proSn" width="150" />
      <el-table-column label="计划生产数量" align="center" prop="planNum" width="105" />
      <el-table-column label="已生产数量" align="center" prop="gbtNum" width="100" />
      <el-table-column label="订单编号" align="center" prop="orderSn" width="170"/>
      <el-table-column label="开工日期" align="center" prop="startWork" width="100" />
<!--      <template slot-scope="scope">-->
<!--        <el-date-picker v-model="scope.row.startDate" type="date" placeholder="选择日期" :disabled="true"></el-date-picker>-->
<!--      </template>-->
      <el-table-column label="创建者" align="center" prop="createdBy" width="100" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:task:edit']"
          >修改</el-button>
          <el-button
            v-if="splitButton[scope.$index].buttonState === 2"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:task:remove']"
          >撤回</el-button>
          <el-button
            v-if="splitButton[scope.$index].buttonState === 1 || taskList[scope.$index].startWork!=null"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleSplit(scope.row,scope.$index)"
            >拆卡</el-button>
          <template>
            <el-dropdown>
              <span class="el-dropdown-link">
                <el-icon class="el-icon-more">
                  </el-icon>
                  更多
                </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button
                      v-if="splitButton[scope.$index].buttonState === 0 && taskList[scope.$index].startWork==null"
                      size="mini"
                      type="text"
                      icon="el-icon-check"
                      @click="openConfirmStartWorkDialog(scope.$index)"
                    >确认开工</el-button>
                  </el-dropdown-item>
<!--                  <el-dropdown-item>-->
<!--                    <el-button-->
<!--                      size="mini"-->
<!--                      type="text"-->
<!--                      icon="el-icon-check"-->
<!--                    >拆卡</el-button>-->
<!--                  </el-dropdown-item>-->
                  <el-dropdown-item>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-check"
                      @click="handleManifest(scope.row,scope.$index)"
                    >领料清单</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button
                      v-if="splitButton[scope.$index].buttonState === 2"
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                    >撤回任务卡</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车间任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-divider class="bom_divider"></el-divider><!--分割线-->
        <el-form-item label="销售单号">
          <el-select v-model="form.orderSn" placeholder="请选择" style="width:100%" @change="handleGetPro">
                        <el-option
                          v-for="item in orderOptions"
                          :key="item.id"
                          :label="`${item.orderName}/${item.orderSn}`"
                          :value="item.orderSn"
                        ></el-option>
                      </el-select>
        </el-form-item>
        <el-form-item label="产品" prop="proId">
          <el-select v-model="form.proId" placeholder="请选择" style="width:100%" @change="handleProChange" :disabled="title=='修改车间任务'||proShow ? false:true">
            <el-option
              v-for="item in productOptions"
              :key="item.proId"
              :label="`${item.proName}/${item.proSn}`"
              :value="item.proId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称:" prop="proName">
              <span>{{ form.proName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编码:" prop="proSn">
              <span>{{ form.proSn }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider class="bom_divider"></el-divider><!--分割线-->
<!--        <el-form-item label="车间任务编号" prop="sn">-->
<!--          <el-input v-model="form.sn" placeholder="请输入车间任务编号" />-->
<!--        </el-form-item>-->
        <el-form-item label="车间任务名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入车间任务名称" />
        </el-form-item>
        <el-form-item label="计划生产数量" prop="planNum">
          <el-input v-model="form.planNum" placeholder="请输入计划生产数量" />
        </el-form-item>
        <el-form-item v-if="title=='修改车间任务'" label="任务状态" prop="state">
          <el-input v-model="form.state" placeholder="请输入任务状态" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 拆卡对话框 -->
    <el-dialog :title="titleSplit" :visible.sync="openSplit" width="1000px" append-to-body>
      <el-form ref="form" :model="formSplit" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="proName">
<!--                <el-input v-model="form.proName" placeholder="请输入车间任务名称" />-->
                <span>{{formSplit.proName}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="proSn">
<!--              <el-input v-model="form.proSn" placeholder="请输入车间任务编号" />-->
              <span>{{formSplit.proSn}}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="车间任务编号" prop="taskSn">
<!--              <el-input v-model="form.taskSn" placeholder="请输入车间任务编号" />-->
              <span>{{formSplit.taskSn}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划生产数量" prop="planNum">
<!--              <el-input v-model="formSplit.planNum" placeholder="请输入计划生产数量" />-->
              <span>{{formSplit.planNum}}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="每卡数量" prop="cardNum">
              <el-input v-model="formSplit.cardNum" placeholder="请输入每卡数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务卡总数" prop="allCardNum">
              <el-input v-model="formSplit.allCardNum" placeholder="请输入任务卡总数,下方根据这个拆卡" @input="handleInput"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="计划开始日期" prop="planStartDate">
              <el-date-picker clearable
                              v-model="formSplit.planStartDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择计划开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束日期" prop="planEndDate">
              <el-date-picker clearable
                              v-model="formSplit.planEndDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择计划结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="物料列表" >
          <el-card shadow="always" style="border-radius: 15px;">
            <el-table border style="width: 100%" v-loading="loading" border :data="mtrs">
              <el-table-column label="物料名称" align="center" prop="proName">
                <template slot-scope="scope">
                  {{ scope.row.proMateriel.matName }}
                </template>
              </el-table-column>
              <el-table-column label="物料编码" align="center" prop="matSn">
                <template slot-scope="scope">
                  {{ scope.row.proMateriel.matSn }}
                </template>
              </el-table-column>
              <el-table-column label="物料价格" align="center" prop="cost">
                <template slot-scope="scope">
                  {{ scope.row.proMateriel.matPrice==undefined?'0元':scope.row.proMateriel.matPrice+'元' }}
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  {{scope.row.matNum}}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-form-item>

        <el-form-item label="任务卡拆卡" >
          <el-card shadow="always" style="border-radius: 15px;">
            <el-table style="border-radius: 15px;" v-loading="loading" border :data="formSplitList">
              <el-table-column label="任务卡编号" align="center" prop="sn">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.sn" placeholder="请输入任务卡编号" />
                </template>
              </el-table-column>
              <el-table-column label="计划生产数" align="center" prop="planNum">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.planNum" placeholder="请输入计划生产数" />
                </template>
              </el-table-column>
              <el-table-column label="生产批号" align="center" prop="cost">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.proLotNumber" placeholder="请输入生产批号" />
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="formSplit.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormSpilit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 领料清单对话框 -->
    <el-dialog :title="titleManifest" :visible.sync="openManifest" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-divider>物料列表</el-divider><!--分割线-->
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table style="border-radius: 15px;" v-loading="loading" :data="formManifestList">
            <el-table-column label="物料名称" prop="matName" :width="150">
              <template slot-scope="scope">
                <el-select v-model="scope.row.matId" filterable placeholder="请选择"
                           @change="(option) => mtrchang(option, scope.$index)">
                  <el-option v-for="item in matOptions" :key="item.id" :label="`${item.matName}/${item.name}`" :value="item.matId">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="物料编码" prop="matSn">
            </el-table-column>
            <el-table-column label="物料库" prop="strmName">
            </el-table-column>
            <el-table-column label="供应商" prop="supplierName">
              <template slot-scope="scope">
                <el-select v-model="scope.row.supplierId" filterable placeholder="请选择">
                  <el-option v-for="item in supOptions" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="仓库容量" :width="280">
              <template slot-scope="scope">
                <el-row type="flex" align="middle">
                  <el-col :span="10">
                    <span>总容量: {{ scope.row.strmNum }}</span>
                  </el-col>
                  <el-col :span="14">
                    <span>可用容量: {{ scope.row.strmNum-scope.row.strmRenum }}</span>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column label="出库数量" prop="num">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.num" controls-position="right"  :min="1" :max="10"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button  size="mini" type="text" icon="el-icon-check" @click="mtroutadd(scope.$index)">增加</el-button>
                <el-button  size="mini" type="text" icon="el-icon-check" @click="mtroutdel(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormManifest">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 确认开工对话框 -->
    <el-dialog :visible.sync="confirmStartWorkDialogVisible" title="确认开工" width="30%">
      <el-form :model="confirmStartWorkForm">
        <el-form-item label="开工日期" :label-width="formLabelWidth">
          <el-date-picker v-model="confirmStartWorkForm.startWork" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="confirmStartWorkDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmStartWork">确认开工</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {listTask, getTask, delTask, addTask, updateTask, getMatTask, updateStartWork,addCardTask, addPickTask} from "@/api/mes/task";
import Vue from "vue";
import {getSell_orderPro, listSell_order} from "@/api/mes/sell_order";
import {listPro_design} from "@/api/mes/pro_design";
import {getBomMat} from "@/api/mes/bom";
import {listSupplier} from "@/api/mes/supplier";

export default {
  name: "Task",
  dicts:["task_state"],
  data() {
    return {
      //拆卡按钮是否显示，0为显示确认开工，1为显示拆卡，2为显示撤回
      splitButton:[],
      proShow:false,
      //记录数据行数
      confirmCount:0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //订单选项
      orderOptions:[],
      //订单对应产品选项
      productOptions:[],
      //物料库房选项
      matOptions:[],
      //供应商选项
      supOptions:[],
      //物料列表
      mtrs:[],
      // 车间任务表格数据
      taskList: [],
      dialogFormVisible: false,
      formLabelWidth: '140px',
      confirmStartWorkDialogVisible: false,
      confirmStartWorkForm:{
        startData:null,
      },
      // 弹出层标题
      title: "",
      titleSplit: "",
      titleManifest:"",
      // 是否显示弹出层
      open: false,
      openSplit:false,
      openManifest:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sn: null,
        orderSn: null,
      },
      queryParamsOrder: {
        orderSn: null,
        orderName: null,
      },
      // 查询参数
      queryParamsPro: {
        proName: null,
        proType: null,
      },
      queryParamsSupplier: {
        name: null,
        supSn: null,
        supType: null,
      },
      // 表单参数
      form: {},
      formSplit: {},
      formSplitList:[],
      formManifestList: [{
        matId:null,
        matName:null,
        matSn:null,
        strmId:null,
        strmName:null,
        strmSn:null,
        strmNum:null,
        strmRenum:null,
        dfsNum:null,
        supplierId:null,
        supplierName:null,
      }],
      //定义Map
      myMap: new Map(),
      // 表单校验
      rules: {
        sn: [
          { required: true, message: "车间任务编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getOrderList();
    this.getSupplier();
    this.myMap.set( 0,'成品');
    this.myMap.set( 1,'半成品');
    this.myMap.set( 2,'原材料');
  },
  methods: {
    mtrchang(option, index) {
      let ss = this.matOptions.find(item => item.matId == option)
      this.formManifestList[index].matName = ss.matName;
      this.formManifestList[index].matSn= ss.matSn;
      this.formManifestList[index].matId = ss.matId;
      this.formManifestList[index].strmId = ss.strmId;
      this.formManifestList[index].strmName = ss.name;
      this.formManifestList[index].strmSn = ss.sn;
      // this.formManifestList[index].proNum = ss.proNum;
      this.formManifestList[index].strmNum = ss.strmNum;
      this.formManifestList[index].strmRenum = ss.strmRenum;
      this.formManifestList[index].sptkId = this.taskList[this.confirmCount].id;
      this.formManifestList[index].sptkSn = this.taskList[this.confirmCount].sn;
      console.log(this.matOptions,"物料数组")
    },
    /**
     * 删除物料
     * @param {下标} index
     */
    mtroutdel(index) {
      if(index!=0){
        this.formManifestList.splice(index, 1);
        console.log(index,"!!!!!!!!!!!!!!!!!!!!!!")
      }
    },

    /**
     * 添加物料
     * @param {下标} index
     * @param {行数据} row
     */
    mtroutadd(index) {
      console.log("formManifestList",this.formManifestList)
      if (index != undefined) {
        this.formManifestList.push(
          {
            matId:null,
            matName:null,
            matSn:null,
            strmId:null,
            strmName:null,
            strmSn:null,
            strmNum:null,
            strmRenum:null,
            dfsNum:null,
            supplierId:null,
            supplierName:null,
          })
      }
    },
    getSupplier(){

      listSupplier(this.queryParamsSupplier).then(response =>{
              this.supOptions = response.rows;
              console.log('供应商选项信息:',this.supOptions);
     });

    },
    //拆分任务卡功能
    handleInput(){
      console.log("4555456",this.formSplit)
      if(this.formSplit.allCardNum != ''){
        var plannum=this.formSplit.planNum;
        this.formSplitList = new Array(parseInt(this.formSplit.allCardNum)).fill(null).map(function(_, index) {
          // 根据车间编号和索引生成 cardSn
          var cardsn = this.formSplit.taskSn + '-' + (index + 1);
          // 生成当前日期时间的字符串，格式为yyyyMMddHHmm
          var now = new Date();
          var year = now.getFullYear();
          var month = (now.getMonth() + 1).toString().padStart(2, '0');
          var day = now.getDate().toString().padStart(2, '0');
          var seconds = now.getSeconds().toString().padStart(2, '0');
          var proLotNumber = `${year}${month}${day}${seconds}-000${index}`;
          //判断每个任务卡的计划生产数量
          // 如果存在名为 'cardNum' 的属性，执行相应的操作
          if ('cardNum' in this.formSplit)
          {
            if(this.formSplit.cardNum !='')
            {
              this.formSplit.cardNum = parseInt(this.formSplit.cardNum)
              if(this.formSplit.cardNum>plannum)
               {
                 var planNum=0;
               }
              else
               {
                 var planNum= this.formSplit.cardNum;
                 plannum = plannum - this.formSplit.cardNum;
               }
            }
          }

          return {
            cardId: null,
            planNum: planNum,
            proLotNumber: proLotNumber,
            sn: cardsn,
            planStartDate: this.formSplit.planStartDate,
            planEndDate: this.formSplit.planEndDate,
            sptkId: this.formSplit.taskId,
            sptkSn: this.formSplit.taskSn,
          };
        }.bind(this));
        console.log("455545677777",this.formSplitList)
      }
    },
    //给拆分界面产品赋值
    handleProChange() {
        // 根据 form.proId 找到对应的存址
        this.form.proId = parseInt(this.form.proId);
        const selectedProduct = this.productOptions.find(option => option.proId === this.form.proId);
        if (selectedProduct) {
          // console.log(selectedProduct, "handleProChange!")
          // 更新其他输入框的值
          this.form.proName = selectedProduct.proName;
          this.form.proSn = selectedProduct.proSn;
        }
    },
    //获取对应订单的产品信息
    handleGetPro(){
      const order = this.orderOptions.find(order => order.orderSn === this.form.orderSn);
      // console.log("rese",order.id)
      const orderId = order.id
      getSell_orderPro(orderId).then(response => {
        this.productOptions = response.rows;
        this.proShow=true;
      });
    },
    /** 查询销售订单列表 */
    getOrderList() {
      listSell_order(this.queryParamsOrder).then(response => {
        this.orderOptions = response.rows;
        this.total = response.total;
      });
    },
    /** 查询车间任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.taskList.forEach((item, index) => {
          Vue.set(this.splitButton, index, {buttonState: 0});
        });
        this.total = response.total;
        this.loading = false;
        this.calculateIndex()
      });
    },
    /** 计算列表编号 */
    calculateIndex() {
      this.taskList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSplit = false;
      this.openManifest= false;
      this.proShow=false;
      this.reset();
    },
    //根据计划生产数量和已生产数量计算生产进度的比值
    calculateProgressPercentage(planNum, gbtNum) {
      // 确保计划生产数量和已生产数量都是数字
      if (isNaN(planNum) || isNaN(gbtNum)) {
        return 0;
      }
      if (planNum === 0) {
        // 避免除以零的情况
        return 0;
      }
      // 计算百分比并四舍五入
      return Math.round((gbtNum / planNum) * 100);
    },
    openConfirmStartWorkDialog(index) {
      this.confirmStartWorkDialogVisible = true;
      // 初始化开工日期为当前时间
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
      const day = currentDate.getDate().toString().padStart(2, '0');
      this.confirmStartWorkForm.startWork = `${year}-${month}-${day}`;
      this.confirmCount=index;
    },
    confirmStartWork() {
      // 处理确认开工的逻辑
      console.log('确认开工');
      // 获取当前行的ID
      const currentRow = this.taskList[this.confirmCount];
      const taskId = currentRow.id;
      console.log("车间任务id",taskId)
      // this.confirmStartWorkDialogVisible = false;
      this.splitButton[this.confirmCount].buttonState=1;
      this.taskList[this.confirmCount].startWork=this.confirmStartWorkForm.startWork;
      //更新开工时间
      updateStartWork({id:taskId,startWork:this.confirmStartWorkForm.startWork}).then(response => {
        console.log("开工日期",this.confirmStartWorkForm.startWork)
        this.$modal.msgSuccess("开工成功");
        this.getList();
      }).catch(() =>{
        this.$modal.msgError("开工失败");
      });
      this.confirmStartWorkDialogVisible = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        materId: null,
        proId: null,
        name: null,
        state: null,
        planNum:null,
        gbtNum: null,
        orderSn: null,
        isDeleted: null,
        startTime:null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null
      };
      this.formSplit={
        proName:null,
        proSn:null,
        taskId:null,
        taskSn:null,
        planNum:null,
        planStartDate:null,
        planEndDate:null,
        remark:null,
      }
      this.resetForm("form");
      this.resetForm("formSplit");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车间任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        const order = this.orderOptions.find(order => order.orderSn === this.form.orderSn);
        if(order)
        {
          const orderId = order.id
          getSell_orderPro(orderId).then(response => {
            this.productOptions = response.rows;
            this.handleProChange()
            this.proShow=true;
          });
        }
        this.open = true;
        this.title = "修改车间任务";
      });

    },
    /** 拆卡按钮操作 */
    handleSplit(row,index) {
      this.reset();
      this.confirmCount=index;
      const id = parseInt(row.proId)
      listPro_design(this.queryParamsPro).then(response => {
        this.productOptions = response.rows;
        const product = this.productOptions.find(item => item.id === id)
       if(product){
         const bomId=product.proBomId
         if(bomId!=null){
           getBomMat(bomId).then(response => {
             this.mtrs = response;
             console.log("54168489",response)
           });
         }
         getBomMat(53).then(response => {
           this.mtrs = response;
           console.log("54168489",response)
         });
         this.formSplit.proName=product.proName;
         this.formSplit.proSn=product.proSn;
       }
      });
      this.formSplit.taskId=row.id;
      this.formSplit.taskSn=row.sn;
      this.formSplit.planNum=row.planNum;
      this.openSplit = true;
      this.titleSplit = "生成车间任务卡";0
    },

    /**领料清单按钮操作 */
    handleManifest(row,index) {
      this.reset();
      this.confirmCount=index;
      const proId = row.proId
      getMatTask(proId).then(response => {
          this.matOptions = response.rows;
          console.log(" this.matOptions", this.matOptions)
          });
      this.openManifest = true;
      this.titleManifest = "领料清单";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
          this.proShow=false;
        }
      });
    },
    submitFormSpilit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.splitButton[this.confirmCount].buttonState=2;
          addCardTask(this.formSplitList).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.splitButton[this.confirmCount].buttonState=2;
            this.open = false;
            this.getList();
          })
        }
      });
    },

    submitFormManifest() {
          addPickTask(this.formManifestList).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除车间任务编号为"' + ids + '"的数据项？').then(function() {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
